#!/usr/local/bin/perl

use strict;
use Getopt::Std;

use NBU;

my %opts;
getopts('csd', \%opts);
$opts{'c'} = 1;

NBU::->debug($opts{'d'});

my $master;
if ($opts{'M'}) {
  $master = NBU::Host->new($opts{'M'});
}
else {
  my @masters = NBU->masters;  $master = $masters[0];
}
my $me = NBU->me;
my @mediaManagers;
foreach my $server (NBU::StorageUnit->mediaServers($master)) {
  if (NBU::Drive->populate($server)) {
    push @mediaManagers, $server;
  }
}


my $hdr = "Date,\"Tape SN\",\"Robot Number\",\"Drive Position\",\"Drive Index\",\"Error Code\",Recoverable,\"Recovery Method\"\n";
print $hdr if ($opts{'c'});

my $totalErrors;
my %media;
my %driveErrors;
my %driveLastFailure;

open(LOG, "</usr/openv/netbackup/db/media/errors");

while (<LOG>) {
  my ($dt, $tm, $mediaID, $driveIndex, $errorCode) = split;

  my $drive = NBU::Drive->byIndex($driveIndex, $me);

  if (!defined($drive)) {
    print STDERR "Can no longer identify drive index $driveIndex\n";
    next;
  }

  my $drivePosition = "-";
  my $robotNumber = "-";

  if (defined($drive->robot)) {
    $drivePosition = $drive->robotDriveIndex;
    $robotNumber = $drive->robot->id;
  }

  $totalErrors += 1;
  $media{$mediaID} += 1;
  $driveErrors{$driveIndex} += 1;
  $driveLastFailure{$driveIndex} = $dt." ".$tm;

  print "\"$dt $tm\",$mediaID,$robotNumber,$drivePosition,$driveIndex,\"$errorCode\",,,\n"
    if ($opts{'c'});
}

if (!$opts{'c'}) {
  foreach my $d (sort {$driveErrors{$a} <=> $driveErrors{$b}} (keys %driveErrors)) {
    print "Drive $d had $driveErrors{$d} errors most recently on ".
      "$driveLastFailure{$d}\n";
  }
}
